using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;  
using System.Net.Sockets;
using System.IO;
using System.Net;

namespace Client
{
    public partial class Form1 : Form
    {
        private NetworkStream output; // stream for receiving data           
        private BinaryWriter writer; // facilitates writing to the stream    
        private BinaryReader reader; // facilitates reading from the stream  
        private Thread readThread; // Thread for processing incoming messages
        private string message = "";
        //private string IPService = "10.0.83.35";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Message mess = new Message();
            mess.Header = "123456";
            mess.TypeIndentifier = "1234";
            mess.PrimaryBitMap = "1234567890123456";
            mess.ProcessingCode = "123456";
            mess.ResponseCode = "12";
            //mess.UserID = "1234567890123456";
            //mess.OTPNumber = "1234";
            mess.UserID = txtUserID.Text;
            mess.OTPNumber = txtOTP.Text;
            //MessageBox.Show(mess.Content);
            writer.Write(mess.Content);            
        }

        private void Form1_Load(object sender, EventArgs e)
        {            
            readThread = new Thread(new ThreadStart(RunClient));
            readThread.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

            if(writer!=null)
                writer.Write("-11");  //inform server disconnect!            
            if (readThread != null)
            {                
            }
            System.Environment.Exit(System.Environment.ExitCode);

        }

        // connect to server and display server-generated text
        public void RunClient()
        {
            TcpClient client;
            // instantiate TcpClient for sending data to server
            try
            {
                //MessageBox.Show("Attempting connection\r\n","Client");

                // Step 1: create TcpClient and connect to server                
                client = new TcpClient();
                client.Connect(GetIPAddress(), 1917);            

                // Step 2: get NetworkStream associated with TcpClient
                output = client.GetStream();                          

                // create objects for writing and reading across stream
                writer = new BinaryWriter( output );                   
                reader = new BinaryReader( output );

                do
                {                    
                    // Step 3: processing phase
                    try
                    {
                        // read message from server                                              
                        message = reader.ReadString();
                        //MessageBox.Show(message);
                        //string strUserID = message.Substring(34, 16);
                        //string strOTPNumber = message.Substring(50, 6);
                        //MessageBox.Show("SERVER UserID: " + strUserID + "   OTPNum: " + strOTPNumber);
                        if (message == "00"){                       
                            MessageBox.Show("Login Successful");
                        }
                        else {                     
                            MessageBox.Show("fault! Error: " + message);
                        }
                        //MessageBox.Show("Success: " + successNum + "  fault: " + faultNum);
                    } // end try
                    catch ( Exception e)
                    {
                        MessageBox.Show("Error " + e.Message);
                        // handle exception if error in reading server data
                        System.Environment.Exit( System.Environment.ExitCode );
                    } // end catch
                } while ( message != "-11" );
                
                // Step 4: close connection
                writer.Close();
                reader.Close();
                output.Close();
                client.Close();
                MessageBox.Show("CLIENT: " + message, "Client");
                Application.Exit();
            } // end try
            catch ( Exception error )
            {
                // handle exception if error in establishing connection
                MessageBox.Show( error.ToString(), "Connection Error",MessageBoxButtons.OK, MessageBoxIcon.Error );
                System.Environment.Exit( System.Environment.ExitCode );
            } // end catch
        }
        private string GetIPAddress()
        {
            string strHostName = "";
            string ipaddr = "";
            strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            for (int i = 0; i < addr.Length; i++)
            {
                ipaddr = addr[i].ToString();
            }
            return ipaddr;
        }

    }
}